package net.diaowen.dwsurvey.controller;

import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.dwsurvey.entity.Question;
import net.diaowen.dwsurvey.entity.SurveyAnswer;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.entity.SurveyStats;
import net.diaowen.dwsurvey.service.SurveyAnswerManager;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;
import net.diaowen.dwsurvey.service.SurveyStatsManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by keyuan on 17/7/31.
 */
@Controller
@RequestMapping("/sy/user/survey-admin")
public class SurveyAdminController {

    @Autowired
    private SurveyDirectoryManager directoryManager;
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private SurveyStatsManager surveyStatsManager;
    @Autowired
    private SurveyAnswerManager surveyAnswerManager;


    @RequestMapping("/list.do")
    public ModelAndView list(Page<SurveyDirectory> page,String surveyName,Integer surveyState) throws Exception {

        page=directoryManager.findPage(page,surveyName,surveyState,null);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("page",page);
        modelAndView.addObject("surveyState",surveyState);
        modelAndView.addObject("surveyName",surveyName);
        modelAndView.setViewName("/diaowen-surveyadmin/list");
        return modelAndView;
    }

    @RequestMapping("/defaultReport.do")
    public ModelAndView defaultReport(String surveyId) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        // 得到频数分析数据
        SurveyDirectory directory=directoryManager.getSurvey(surveyId);
        if(directory!=null){
            List<Question> questions = surveyStatsManager.findFrequency(directory);
            SurveyStats surveyStats = new SurveyStats();
            surveyStats.setQuestions(questions);
            modelAndView.addObject("surveyStats",surveyStats);
            modelAndView.addObject("directory",directory);
        }
        modelAndView.addObject("surveyId",surveyId);
        modelAndView.setViewName("/diaowen-surveyadmin/default-report");
        return modelAndView;
    }

    @RequestMapping("/delete.do")
    @ResponseBody
    public String delete(String id) throws Exception {
        String result="false";
        try{
            User user = accountManager.getCurUser();
            if(user!=null){
                String userId=user.getId();
                SurveyDirectory surveyDirectory=directoryManager.getSurvey(id);
                if(surveyDirectory!=null){
                    directoryManager.delete(id);
                    result="true";
                }
            }
        }catch (Exception e) {
            result="false";
        }
        return result;
    }


    @RequestMapping("/answer.do")
    public ModelAndView execute(HttpServletRequest request, Page<SurveyAnswer> page, String surveyId) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        User user=accountManager.getCurUser();
        if(user!=null){
            SurveyDirectory survey=directoryManager.getSurvey(surveyId);
            if(survey!=null){
                page=surveyAnswerManager.answerPage(page, surveyId);
            }
            modelAndView.addObject("page",page);
            modelAndView.addObject("survey",survey);
        }
        modelAndView.addObject("surveyId",surveyId);
        modelAndView.setViewName("/diaowen-surveyadmin/survey-answer-data");
        return modelAndView;
    }

    @RequestMapping("/responseAnswer.do")
    public ModelAndView responseAnswer(String answerId) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<Question> questions = new ArrayList<Question>();
        try {
            SurveyDirectory directory=new SurveyDirectory();
            if (answerId != null) {
                SurveyAnswer answer = surveyAnswerManager.getModel(answerId);
                questions = surveyAnswerManager.findAnswerDetail(answer);
                User user=accountManager.getCurUser();
                if(answer.getSurveyId() != null && user!=null){
                    SurveyDirectory survey=directoryManager.getSurvey(answer.getSurveyId());
                    if(survey!=null){
                        modelAndView.addObject("questions", questions);
                        modelAndView.addObject("directory", directory);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        modelAndView.setViewName("/diaowen-answer/response-answer");
        return modelAndView;
    }

    @RequestMapping("/delete-answer.do")
    @ResponseBody
    public String deleteAnswer(String answerId) throws Exception {
        String result="error";
        try{
            if (answerId != null) {
                SurveyAnswer answer = surveyAnswerManager.getModel(answerId);
                User user=accountManager.getCurUser();
                if(answer.getSurveyId() != null && user!=null){
                    SurveyDirectory survey=directoryManager.getSurvey(answer.getSurveyId());
                    if(survey!=null){
                        surveyAnswerManager.delete(answer);
                        Integer answerNum = survey.getAnswerNum();
                        if(answerNum!=null && answerNum>=1) {
                            survey.setAnswerNum(answerNum-1);
                            directoryManager.save(survey);
                        }
                    }
                }
            }
            result="true";
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/exportXLS.do")
    @ResponseBody
    public String exportXLS(HttpServletRequest request, HttpServletResponse response, String surveyId) throws Exception{
        try{
            String savePath = request.getSession().getServletContext().getRealPath("/");
            User user=accountManager.getCurUser();
            if(user!=null){
                SurveyDirectory survey=directoryManager.getSurvey(surveyId);
                if(survey!=null){
                    savePath=surveyAnswerManager.exportXLS(surveyId,savePath);
//					savePath = URLEncoder.encode(savePath, "utf-8");
                    response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("dwsurvey_"+survey.getSid()+".xls", "UTF-8"));
//                    response.sendRedirect(request.getContextPath()+savePath);
                    request.getServletContext().getRequestDispatcher(savePath).forward(request,response);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
